package mylittleinvestigations.PersistentThreads;

import java.util.concurrent.Semaphore;
import java.util.logging.Level;
import java.util.logging.Logger;
import mylittleinvestigations.MouseHelper;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;

public class InputThread implements Runnable
{
    private static InputThread instance;
    
    public static InputThread getInstance()
    {
        if (instance == null)
        {
            instance = new InputThread();
        }
        
        return instance;
    }
    
    private Thread inputThread;
    private int screenHeight;
    
    private boolean isMouseLeftButtonDown;
    
    private volatile boolean isRunning;
    
    private Semaphore processInputSemaphore;
    private Semaphore stoppedSemaphore;
    
    public void Init(int screenHeight)
    {
        this.screenHeight = screenHeight;
        this.isMouseLeftButtonDown = false;
        this.isRunning = true;
        this.processInputSemaphore = new Semaphore(0);
        this.stoppedSemaphore = new Semaphore(0);
        
        this.inputThread = new Thread(this);
        this.inputThread.setName("MLI Input Thread");
        this.inputThread.setPriority(Thread.NORM_PRIORITY);
        this.inputThread.start();
    }
    
    public void PollInput()
    {
        if (this.processInputSemaphore.availablePermits() == 0)
        {
            this.processInputSemaphore.release();
        }
    }
    
    public void Stop()
    {
        this.isRunning = false;
        this.processInputSemaphore.release();
    }
    
    public void WaitUntilStopped()
    {
        try
        {
            this.stoppedSemaphore.acquire();
        }
        catch (InterruptedException ex)
        {
            Logger.getLogger(InputThread.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void run()
    {
        while (this.isRunning)
        {
            try
            {
                this.processInputSemaphore.acquire();
            }
            catch (InterruptedException ex)
            {
                Logger.getLogger(InputThread.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            while (Mouse.next())
            {
                if (Mouse.getEventButton() == 0)
                {
                    this.isMouseLeftButtonDown = Mouse.getEventButtonState();
                }
            }
            
            MouseHelper.Update(this.isMouseLeftButtonDown, Mouse.getX(), this.screenHeight - Mouse.getY());
        }
        
        this.stoppedSemaphore.release();
    }
}
